package org.jet.emall.rbac.service;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.jet.emall.common.exception.CustomServiceException;
import org.jet.emall.common.restful.result.CommonPage;
import org.jet.emall.rbac.dto.AdminUserViewDTO;
import org.jet.emall.rbac.dto.NewAdminUserDTO;
import org.jet.emall.rbac.dto.UpdateAdminUserDTO;
import org.jet.emall.rbac.po.AdminUser;
import org.jet.emall.rbac.po.AdminUserRole;
import org.jet.emall.rbac.po.AdminUserView;
import org.jet.emall.rbac.service.mp.IAdminUserRoleService;
import org.jet.emall.rbac.service.mp.IAdminUserService;
import org.jet.emall.rbac.service.mp.IAdminUserViewService;
import org.jet.emall.rbac.transfer.AdminUserDtoTransfer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author xiaozai
 * @version 1.0
 * @date 2020-04-05 10:31
 */

@Service
public class CustomAdminUserServiceImpl implements CustomAdminUserService {

    /**
     * 引入MP生成的Service来做处理，因为这个Service接口丰富
     */
    @Autowired
    private IAdminUserViewService adminUserViewService;
    @Autowired
    private IAdminUserService adminUserService;
    @Autowired
    private IAdminUserRoleService adminUserRoleService;

    @Override
    public CommonPage<AdminUserViewDTO> page(String query, Integer pageNum, Integer pageSize) {
        IPage<AdminUserView> page = new Page<>();
        page.setCurrent(pageNum).setSize(pageSize);
        Wrapper<AdminUserView> wrapper = new QueryWrapper<>();

        if(StringUtils.isNotBlank(query)) {
            ((QueryWrapper<AdminUserView>) wrapper).like("username", query)
                    .or().like("realname", query)
                    .or().like("email", query)
                    .or().like("phone", query)
                    .or().like("role_name", query);
        }

        adminUserViewService.page(page,wrapper);
        return new CommonPage<AdminUserViewDTO>()
            .setPageNum(page.getCurrent())
            .setPageSize(page.getSize())
            .setTotal(page.getTotal())
            .setTotalPage(page.getPages())
            .setList(AdminUserDtoTransfer.INSTANCE.toDtoList(page.getRecords()));

    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void save(NewAdminUserDTO newUser) {
        AdminUser adminUser = AdminUserDtoTransfer.INSTANCE.toPo(newUser);
        adminUserService.save(adminUser);
        AdminUserRole adminUserRole = new AdminUserRole().setRid(newUser.getRoleId()).setUid(adminUser.getId());
        adminUserRoleService.save(adminUserRole);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<Integer> ids) {
        if(ids.contains(1)){
            throw new CustomServiceException("ID为1的系统特权用户禁止删除");
        }
        Wrapper<AdminUserRole> wrapper = new QueryWrapper<>();
        ((QueryWrapper<AdminUserRole>) wrapper).in("uid",ids);
        adminUserRoleService.remove(wrapper);
        adminUserService.removeByIds(ids);

    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void update(UpdateAdminUserDTO updateAdminUserDTO) {
        if(updateAdminUserDTO.getId().equals(1)){
            throw new CustomServiceException("ID为1的系统特权用户禁止修改");
        }
        AdminUser adminUser = AdminUserDtoTransfer.INSTANCE.toPo(updateAdminUserDTO);
        adminUserService.updateById(adminUser);
        if(updateAdminUserDTO.getRoleId() != null){
            Wrapper<AdminUserRole> wrapper = new QueryWrapper<>();
            ((QueryWrapper<AdminUserRole>) wrapper).eq("rid",updateAdminUserDTO.getRoleId())
                .eq("uid",adminUser.getId());
            AdminUserRole adminUserRole = adminUserRoleService.getOne(wrapper);
            if(adminUserRole==null){
                adminUserRoleService.save(new AdminUserRole().setUid(adminUser.getId()).setRid(updateAdminUserDTO.getRoleId()));
            }
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void toggleUserStatus(List<Integer> ids, Byte state) {
        if(ids.contains(1)){
            throw new CustomServiceException("ID为1的系统特权用户禁止修改");
        }
        AdminUser adminUser = new AdminUser();
        adminUser.setStatus(state);
        Wrapper<AdminUser> wrapper = new UpdateWrapper<>();
        ((UpdateWrapper<AdminUser>) wrapper).in("id",ids);
        adminUserService.update(adminUser,wrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void assignRole(Integer id, Integer roleId) {
        if(id.equals(1)){
            throw new CustomServiceException("ID为1的系统特权用户禁止修改");
        }
        Wrapper<AdminUserRole> wrapper = new QueryWrapper<>();
        ((QueryWrapper<AdminUserRole>) wrapper).eq("uid",id);
        AdminUserRole adminUserRole = adminUserRoleService.getOne(wrapper);
        if(adminUserRole!=null){
            if(!adminUserRole.getRid().equals(roleId)){
                adminUserRole.setRid(roleId);
                adminUserRoleService.updateById(adminUserRole);
            }
        }else{
            adminUserRoleService.save(new AdminUserRole().setUid(id).setRid(roleId));
        }

    }

    @Override
    public AdminUserViewDTO findById(Integer id) {
        AdminUserView adminUserView = adminUserViewService.getById(id);
        AdminUserViewDTO adminUserViewDTO = AdminUserDtoTransfer.INSTANCE.toDto(adminUserView);
        return adminUserViewDTO;
    }
}
